package com.hui.java.concurrency;

/**
 * TODO: 线程T1,T2,T3实现顺序（T1->T2->T3）执行？
 *
 * @author chenth
 * @create 2019-04-14 22:44
 **/
public class ThreadExecutionQuestion {

    public static void main(String[] args) throws InterruptedException {
        threadOneByOne();
        thredLoop();
        threadSleep();
        threadWait();
    }

    private static void threadOneByOne()throws InterruptedException{
        Thread t1 = new Thread(ThreadExecutionQuestion::action,"t1");
        Thread t2 = new Thread(ThreadExecutionQuestion::action,"t2");
        Thread t3 = new Thread(ThreadExecutionQuestion::action,"t3");

        //启动,但是没有按照顺序
//        t1.start();
//        t2.start();
//        t3.start();

        //通过加上join,效果也是一样，没有顺序
//        t1.join();
//        t2.join();
//        t3.join();

        //正确的写法，在每次启动之后，再join
        t1.start();
        t1.join();

        t2.start();
        t2.join();

        t3.start();
        t3.join();
    }

    private static void action() {
        System.out.printf("线程[%s] 正在执行。。。\n",Thread.currentThread().getName());
    }

    /**
     * 第二种实现方法
     */
    private static void thredLoop(){
        Thread t4 = new Thread(ThreadExecutionQuestion::action,"t4");
        Thread t5 = new Thread(ThreadExecutionQuestion::action,"t5");
        Thread t6 = new Thread(ThreadExecutionQuestion::action,"t6");

        t4.start();
        while (t4.isAlive()){
            //自旋 Spin
        }

        t5.start();
        while (t5.isAlive()){

        }

        t6.start();
        while(t6.isAlive()){

        }
    }

    /**
     * 第三种
     */
    private static void threadSleep() throws InterruptedException {
        Thread t7 = new Thread(ThreadExecutionQuestion::action,"t7");
        Thread t8 = new Thread(ThreadExecutionQuestion::action,"t8");
        Thread t9 = new Thread(ThreadExecutionQuestion::action,"t9");

        t7.start();
        while (t7.isAlive()){
            Thread.sleep(0);
        }

        t8.start();
        while (t8.isAlive()){
            Thread.sleep(0);
        }

        t9.start();
        while (t9.isAlive()){
            Thread.sleep(0);
        }

    }

    /**
     * 第四种
     */
    private static void threadWait()throws InterruptedException{
        Thread t10 = new Thread(ThreadExecutionQuestion::action,"t10");
        Thread t11 = new Thread(ThreadExecutionQuestion::action,"t11");
        Thread t12 = new Thread(ThreadExecutionQuestion::action,"t12");

        threadStartAndWait(t10);
        threadStartAndWait(t11);
        threadStartAndWait(t12);
    }

    private static void threadStartAndWait(Thread thread){
        if(Thread.State.NEW.equals(thread.getState())){
            thread.start();
        }
        while (thread.isAlive()){
            synchronized (thread){
                try {
                    thread.wait();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
